#include "bga/system/ResourceLocator.h"
#include "bga/system/BoardHellException.h"

#include <fstream>
#include <iostream>

using namespace std;

namespace bga
{

ResourceLocator::ResourceLocator()
{
    this->paths.push_back(""); /// We insert the current directory
    parseFile();
}

ResourceLocator::~ResourceLocator()
{

}

void ResourceLocator::parseFile()
{
    /// We assume here that the filename will always be resources.bga
    ifstream file("resources.bga", ios::in);
    if(!file.good())
    {
        createFile();
    }
    else
    {
        string s;
        while(file >> s)
        {
            this->paths.push_back(s);
        }
        file.close();
    }
}

void ResourceLocator::createFile()
{
    ofstream file("resources.bga", ios::out);
    /*if(file.good())
    {
        file << "#Drawable" << endl;
        file << "#Texture2D" << endl;
        file << "#Sound" << endl;
    }*/
}

std::string ResourceLocator::findCompletePath(const std::string& filename)
{
    string s;
    for(unsigned int i = 0; i < this->paths.size(); i++)
    {
        s.clear();
        s = this->paths[i] + filename;
        cout << s << endl;

        if(ifstream(s.c_str(), ios::in).good())
        {
            break;
        }
    }
    return s;
}

File ResourceLocator::findFile(const File& file)
{
    File fileToReturn;
    for(unsigned int i = 0; i < this->paths.size(); i++)
    {
        fileToReturn = File(this->paths[i] + file.getFullName());

        if(fileToReturn.exists())
        {
            return fileToReturn;
        }
    }
    throw BoardHellException("File not found");
}

File ResourceLocator::findFile(const std::string& file)
{
    File fileToReturn;
    for(unsigned int i = 0; i < this->paths.size(); i++)
    {
        if(File::exists(file, this->paths[i]))
        {
            return File(this->paths[i] + file);
        }
    }
    throw BoardHellException("File not found");
}

vector<string> ResourceLocator::getPaths(const std::string& type)
{
    vector<string> pathsArray;
    /*Node<string>* currentNode = this->resourcesDir.getRoot().getLeftChild();
    /// Create an iterator

    /// We look for the good category
    while(currentNode != NULL)
    {
        if(*(currentNode->getElement()) == type)
        {
            break;
        }
        else
        {
            currentNode = currentNode->getRightChild();
        }
    }

    /// We grab all the paths
    if(currentNode != NULL)
    {
        currentNode = currentNode->getLeftChild();
        while(currentNode != NULL)
        {
            pathsArray.push_back(*(currentNode->getElement()));
            currentNode = currentNode->getRightChild();
        }
    }
*/
    return pathsArray;
}

}
